#include "degfx/font.h"
#include <assert.h>

/**font !Draw multi-line text onto a bitmap
This function draws text on a bitamp.  Newline characters (\r or \r\n)
cause the following text to be placed on the following line. */
void mx_font_bitmap_drawblock(const MX_FONT * font, MX_BITMAP * bitmap, const char *text, int len, int x, int y, const MX_PIXEL fore)
{
	int n = 0;
	const int lineheight = mx_font_height(font);

	/** If the font argument is 0 then the default font be used. */
	if (!font)
		font = MXREF(mx__fontref);
	if (!font)
		font = &MX_FONT_DEFAULT;
	assert(font);

	if (len < 0)
		len = 0x7fff;

	while ((text) && (*text) && (n < len)) {
		int i = 0;
		const char *p = text;

		while ((*p) && (*p != '\r') && (*p != '\n') && (n < len)) {
			p += mx_utf8_len(p);
			++i;
			++n;
		}

		/** The function mx_font_bitmap_draw() function is used internally
                to draw the individual text lines. */
		mx_font_bitmap_draw(font, bitmap, text, i, x, y, fore);

		if (*p == '\r') {
			p += mx_utf8_len(p);
			++n;
		}

		if (*p == '\n') {
			p += mx_utf8_len(p);
			++n;
		}

		y += lineheight;
		text = p;
	}
}

/** The size in pixels of multi-line text
This function determines the area in pixels required to draw text on
a bitamp using mx_font_bitmap_drawblock(). */
void mx_font_blocksize(const MX_FONT * font, const char *text, int len, int *tw, int *th, int *last)
{
	int n = 0;
	const int lineheight = mx_font_height(font);

	/** If the font argument is 0 then the default font be used. */
	if (!font)
		font = MXREF(mx__fontref);
	if (!font)
		font = &MX_FONT_DEFAULT;
	assert(font);

	if (len < 0)
		len = 0x7fff;

	/* Pointer parameters can be 0 and those parameters will be ignored. */
	if (tw)
		*tw = 0;

	if (th)
		*th = lineheight;

	while ((text) && (*text) && (n < len)) {
		int sw, i = 0;
		const char *p = text;
		unsigned newline = false;

		while ((*p) && (*p != '\r') && (*p != '\n') && (n < len)) {
			p += mx_utf8_len(p);
			++i;
			++n;
		}

		sw = mx_font_width(font, text, i);

		if (last)
			*last = sw;

		if ((tw) && (*tw < sw))
			*tw = sw;

		if (*p == '\r') {
			p += mx_utf8_len(p);
			++n;
			newline = true;
		}

		if (*p == '\n') {
			p += mx_utf8_len(p);
			++n;
			newline = true;
		}

		if ((newline) && (th))
			*th += lineheight;

		text = p;
	}
}
